package main

import (
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"enzyme-backend/core/handlers"
	"enzyme-backend/core/middleware"
	"enzyme-backend/core/utils"

	"github.com/gin-gonic/gin"
)

func main() {
	// 设置Gin模式
	gin.SetMode(gin.ReleaseMode)

	// 创建处理器实例
	handler := handlers.NewHandler()

	// 创建Gin引擎
	r := gin.Default()

	// 添加CORS中间件
	r.Use(middleware.CORS())

	// 添加请求头验证中间件
	r.Use(middleware.ValidateHeaders())

	// 设置路由组
	authGroup := r.Group("/auth")
	{
		authGroup.POST("/register", handler.Register)
		authGroup.POST("/login", handler.Login)
		authGroup.POST("/verify", handler.Verify)
		authGroup.POST("/send_code", handler.SendCode)
		authGroup.POST("/remake_pswd", handler.RemakePassword)
	}

	payGroup := r.Group("/pay")
	{
		payGroup.GET("/query", handler.QuerySubscription)
		payGroup.GET("/ordertypes", handler.GetOrderTypes)
		payGroup.POST("/alipay/create", handler.CreateAlipayOrder)
		payGroup.POST("/alipay/success", handler.AlipaySuccess)
		payGroup.POST("/alipay/notify", handler.AlipayNotify)
	}

	configGroup := r.Group("/config")
	{
		configGroup.GET("/fetch", handler.FetchConfig)
		configGroup.GET("/country_list", handler.CountryList)
	}

	proxyGroup := r.Group("/proxy")
	{
		proxyGroup.POST("/register", handler.ProxyRegister)
		proxyGroup.POST("/heartbeat", handler.ProxyHeartbeat)
	}

	// 创建HTTP服务器
	server := &http.Server{
		Addr:    fmt.Sprintf("%s:%d", "127.0.0.1", 8877),
		Handler: r,
	}

	// 启动服务器
	go func() {
		utils.GlobalLogger.Info("服务器启动在 %s:%d...", "127.0.0.1", 8877)
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			utils.GlobalLogger.Fatal("服务器启动失败: %v", err)
		}
	}()

	// 等待中断信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	// 优雅关闭服务器
	utils.GlobalLogger.Info("正在关闭服务器...")
	if err := server.Close(); err != nil {
		utils.GlobalLogger.Error("服务器关闭失败: %v", err)
	}
	utils.GlobalLogger.Info("服务器已关闭")
}
